<!--
 * @Author: MarioGo
 * @Date: 2021-11-06 16:11:28
 * @LastEditTime: 2021-11-06 19:07:41
 * @LastEditors: MarioGo
 * @Description: 文件描述
 * @FilePath: /zheye/src/components/Dropdown.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <div class="dropdown" ref="dropdownRef">
    <a
      class="btn btn-danger dropdown-toggle"
      href="#"
      role="button"
      id="dropdownMenuLink"
      data-bs-toggle="dropdown"
      aria-expanded="false"
      @click.prevent="toggleOpen"
    >
      {{ title }}
    </a>

    <ul
      class="dropdown-menu"
      aria-labelledby="dropdownMenuLink"
      :style="{ display: 'block' }"
      v-if="isOpen"
    >
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import useClickOutside from '../hooks/useClickOutside';
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      required: true,
    },
  },
  setup() {
    const isOpen = ref(false);
    const dropdownRef = ref<null | HTMLElement>(null);
    const toggleOpen = () => {
      isOpen.value = !isOpen.value;
    };
    // 自定义事件
    const isClickOutside = useClickOutside(dropdownRef);
    watch(isClickOutside, () => {
      if (!isClickOutside.value && isOpen.value) {
        isOpen.value = false;
      }
    });
    return {
      toggleOpen,
      isOpen,
      dropdownRef,
    };
  },
});
</script>

<style scoped></style>
